{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "96c80538",
   "metadata": {},
   "source": [
    "# SlideNodeParser\n",
    "\n",
    "[SLIDE](https://arxiv.org/abs/2503.17952) (Sliding Localized Information for Document Extraction) is a chunking method introduced to enhance entity and relationship extraction in long documents, especially for low-resource languages. It was designed to support GraphRAG pipelines by embedding localized context into each chunk without exceeding the context window of the LLM.\n",
    "\n",
    "`SlideNodeParser` faithfully implements a almost similar version of this method to improve downstream retrieval and reasoning quality by generating short, meaningful context using a sliding window of nearby chunks. This technique is proven useful for Graph based Retrieval Augmented Generaration techniques.\n",
    "\n",
    "Here is the technique as outlined in the paper:\n",
    "\n",
    "```\n",
    "Given a document D and a list of base chunks (C1, C2, ..., Ck) segmented by sentence boundaries and token count, SLIDE builds local context for each chunk using a fixed-size sliding window of neighboring chunks. This context is appended to the chunk using an LLM-generated summary.\n",
    "\n",
    "The window size is a hyperparameter defined based on the model’s context length and compute budget. Each chunk Ci is enriched by including a few preceding and succeeding chunks (e.g., 5 on each side), resulting in a total of window_size + 1 inputs sent to the LLM.\n",
    "\n",
    "This process is repeated for every chunk in the document. The result is a collection of chunks embedded with richer, window-specific local context, which significantly improves the quality of knowledge graphs and search retrieval, especially in multilingual or resource-constrained settings.\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d65fe020",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-node-parser-slide"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4974c80c",
   "metadata": {},
   "source": [
    "## Install ipy widgets for progress bars (Optional)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8fc19900",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ipywidgets"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4c1bf80",
   "metadata": {},
   "source": [
    "## Setup Data\n",
    "\n",
    "Here we consider a sample text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d1aad3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "text = \"\"\"Constructing accurate knowledge graphs from long texts and low-resource languages is challenging, as large language models (LLMs) experience degraded performance with longer input chunks.\n",
    "This problem is amplified in low-resource settings where data scarcity hinders accurate entity and relationship extraction.\n",
    "Contextual retrieval methods, while improving retrieval accuracy, struggle with long documents.\n",
    "They truncate critical information in texts exceeding maximum context lengths of LLMs, significantly limiting knowledge graph construction.\n",
    "We introduce SLIDE (Sliding Localized Information for Document Extraction), a chunking method that processes long documents by generating local context through overlapping windows.\n",
    "SLIDE ensures that essential contextual information is retained, enhancing knowledge graph extraction from documents exceeding LLM context limits.\n",
    "It significantly improves GraphRAG performance, achieving a 24% increase in entity extraction and a 39% improvement in relationship extraction for English.\n",
    "For Afrikaans, a low-resource language, SLIDE achieves a 49% increase in entity extraction and an 82% improvement in relationship extraction.\n",
    "Furthermore, it improves upon state-of-the-art in question-answering metrics such as comprehensiveness, diversity and empowerment, demonstrating its effectiveness in multilingual and resource-constrained settings.\n",
    "\n",
    "Since SLIDE enhances knowledge graph construction in GraphRAG systems through contextual chunking, we first discuss related work in GraphRAG and chunking, highlighting their strengths and limitations.\n",
    "This sets the stage for our approach, which builds on GraphRAG by using overlapping windows to improve entity and relationship extraction.\n",
    "2.1 GraphRAG and Knowledge Graphs.\n",
    "GraphRAG (Edge et al., 2024) is an advanced RAG framework that integrates knowledge graphs with large language models (LLMs) (Trajanoska et al., 2023) to enhance reasoning and contextual understanding.\n",
    "Unlike traditional RAG systems, GraphRAG builds a knowledge graph with entities as nodes and relationships as edges, enabling precise and context-rich responses by leveraging the graph’s structure (Edge et al., 2024; Wu et al., 2024).\n",
    "Large language models (LLMs), such as GPT-4, show reduced effectiveness in entity and relationship extraction as input chunk lengths increase, degrading accuracy for longer texts (Edge et al., 2024).\n",
    "They also struggle with relationship extraction in low-resource languages, limiting their applicability (Chen et al., 2024; Jinensibieke et al., 2024).\n",
    "Building upon this work, our approach further enhances knowledge graph extraction by incorporating localized context which improves entity and relationship extraction.\n",
    "2.2 Contextual Chunking.\n",
    "Recent work in RAG systems has explored advanced chunking techniques to enhance retrieval and knowledge graph construction.\n",
    "Günther et al. (2024) implemented late chunking, where entire documents are embedded to capture global context before splitting into chunks, improving retrieval by emphasizing document-level coherence.\n",
    "However, this focus on global embeddings is less suited for knowledge graph construction.\n",
    "Our method instead uses localized context from raw text to retain meaningful relationships for improved entity and relationship extraction.\n",
    "Wu et al. (2024) introduced a hybrid chunking approach for Medical Graph RAG, combining structural markers like paragraphs with semantic coherence to produce self-contained chunks.\n",
    "While effective, this approach relies on predefined boundaries.\n",
    "Our method extends this by generating contextual information from neighboring chunks, enhancing the completeness of knowledge graph construction.\n",
    "Contextual retrieval (Anthropic, 2024) improves accuracy but struggles with longer documents, as embedding each chunk with full document context is computationally expensive and truncates critical information with documents exceeding maximum context length of the model (Jiang et al., 2024; Li et al., 2024).\n",
    "Our overlapping window-based approach addresses these inefficiencies, improving performance in both retrieval and knowledge graph construction.\n",
    "\"\"\"\n",
    "\n",
    "from llama_index.core import Document\n",
    "\n",
    "document = Document(text=text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d20083ad",
   "metadata": {},
   "source": [
    "## Setup LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5aba25c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"sk-...\"  # Replace with your OpenAI API key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eded378a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.embeddings.openai import OpenAIEmbedding\n",
    "from llama_index.llms.openai import OpenAI\n",
    "\n",
    "embed_model = OpenAIEmbedding()\n",
    "llm = OpenAI(model=\"gpt-4o-mini\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5365c1a9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Token count: 759\n"
     ]
    }
   ],
   "source": [
    "# Calculate token count of the text\n",
    "\n",
    "from llama_index.core.utilities.token_counting import TokenCounter\n",
    "\n",
    "token_counter = TokenCounter()\n",
    "token_count = token_counter.get_string_tokens(text)\n",
    "print(f\"Token count: {token_count}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46d94da5",
   "metadata": {},
   "source": [
    "## Setup SlideNodeParser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3263ab2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Lets choose a chunk size of 200 tokens and window size of 5\n",
    "\n",
    "from llama_index.node_parser.slide import SlideNodeParser\n",
    "\n",
    "parser = SlideNodeParser.from_defaults(\n",
    "    chunk_size=200,\n",
    "    window_size=5,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1148328c",
   "metadata": {},
   "source": [
    "### Run the synchronous blocking function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d0953b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "start_time = time.time()\n",
    "nodes = parser.get_nodes_from_documents([document], show_progress=True)\n",
    "end_time = time.time()\n",
    "print(f\"Time taken to parse: {end_time - start_time} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20b66aba",
   "metadata": {},
   "source": [
    "## Lets inspect chunks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56925dc7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- Chunk 1 ---\n",
      "Text: Constructing accurate knowledge graphs from long texts and low-resource languages is challenging, as large language models (LLMs) experience degraded performance with longer input chunks. This problem is amplified in low-resource settings where data scarcity hinders accurate entity and relationship extraction. Contextual retrieval methods, while improving retrieval accuracy, struggle with long documents. They truncate critical information in texts exceeding maximum context lengths of LLMs, significantly limiting knowledge graph construction. We introduce SLIDE (Sliding Localized Information for Document Extraction), a chunking method that processes long documents by generating local context through overlapping windows. SLIDE ensures that essential contextual information is retained, enhancing knowledge graph extraction from documents exceeding LLM context limits. It significantly improves GraphRAG performance, achieving a 24% increase in entity extraction and a 39% improvement in relationship extraction for English. For Afrikaans, a low-resource language, SLIDE achieves a 49% increase in entity extraction and an 82% improvement in relationship extraction.\n",
      "Local Context: assistant: The chunk provided introduces SLIDE (Sliding Localized Information for Document Extraction), a method that addresses the challenges of constructing accurate knowledge graphs from long texts and low-resource languages. It highlights how SLIDE improves knowledge graph extraction by processing long documents with overlapping windows, enhancing entity and relationship extraction performance significantly for both English and Afrikaans languages within the GraphRAG framework.\n",
      "\n",
      "--- Chunk 2 ---\n",
      "Text: Furthermore, it improves upon state-of-the-art in question-answering metrics such as comprehensiveness, diversity and empowerment, demonstrating its effectiveness in multilingual and resource-constrained settings.\n",
      "\n",
      " Since SLIDE enhances knowledge graph construction in GraphRAG systems through contextual chunking, we first discuss related work in GraphRAG and chunking, highlighting their strengths and limitations. This sets the stage for our approach, which builds on GraphRAG by using overlapping windows to improve entity and relationship extraction. 2.1 GraphRAG and Knowledge Graphs. GraphRAG (Edge et al., 2024) is an advanced RAG framework that integrates knowledge graphs with large language models (LLMs) (Trajanoska et al., 2023) to enhance reasoning and contextual understanding.\n",
      "Local Context: assistant: The chunk provided discusses how SLIDE enhances knowledge graph construction in GraphRAG systems through contextual chunking. It also introduces GraphRAG as an advanced framework that integrates knowledge graphs with large language models to enhance reasoning and contextual understanding.\n",
      "\n",
      "--- Chunk 3 ---\n",
      "Text: Unlike traditional RAG systems, GraphRAG builds a knowledge graph with entities as nodes and relationships as edges, enabling precise and context-rich responses by leveraging the graph’s structure (Edge et al., 2024; Wu et al., 2024).\n",
      " Large language models (LLMs), such as GPT-4, show reduced effectiveness in entity and relationship extraction as input chunk lengths increase, degrading accuracy for longer texts (Edge et al., 2024). They also struggle with relationship extraction in low-resource languages, limiting their applicability (Chen et al., 2024; Jinensibieke et al., 2024). Building upon this work, our approach further enhances knowledge graph extraction by incorporating localized context which improves entity and relationship extraction. 2.2 Contextual Chunking. Recent work in RAG systems has explored advanced chunking techniques to enhance retrieval and knowledge graph construction. Günther et al.\n",
      "Local Context: assistant: The chunk provided discusses the unique approach of GraphRAG in constructing knowledge graphs using entities and relationships, highlighting its advantages over traditional RAG systems. It also addresses the challenges faced by large language models in entity and relationship extraction, particularly in longer texts and low-resource languages. The chunk further introduces the enhancement of knowledge graph extraction through localized context and references recent advancements in chunking techniques within RAG systems.\n",
      "\n",
      "--- Chunk 4 ---\n",
      "Text: (2024) implemented late chunking, where entire documents are embedded to capture global context before splitting into chunks, improving retrieval by emphasizing document-level coherence.\n",
      " However, this focus on global embeddings is less suited for knowledge graph construction. Our method instead uses localized context from raw text to retain meaningful relationships for improved entity and relationship extraction. Wu et al. (2024) introduced a hybrid chunking approach for Medical Graph RAG, combining structural markers like paragraphs with semantic coherence to produce self-contained chunks. While effective, this approach relies on predefined boundaries. Our method extends this by generating contextual information from neighboring chunks, enhancing the completeness of knowledge graph construction. Contextual retrieval (Anthropic, 2024) improves accuracy but struggles with longer documents, as embedding each chunk with full document context is computationally expensive and truncates critical information with documents exceeding maximum context length of the model (Jiang et al., 2024; Li et al., 2024).\n",
      "Local Context: assistant: This chunk discusses different chunking approaches in the context of knowledge graph construction within RAG systems. It contrasts the use of global embeddings for document-level coherence with localized context for improved entity and relationship extraction. It also mentions a hybrid chunking approach introduced by Wu et al. for Medical Graph RAG, highlighting the importance of contextual information from neighboring chunks in enhancing knowledge graph completeness.\n",
      "\n",
      "--- Chunk 5 ---\n",
      "Text: Our overlapping window-based approach addresses these inefficiencies, improving performance in both retrieval and knowledge graph construction.\n",
      "\n",
      "Local Context: assistant: The chunk provided discusses an overlapping window-based approach that aims to address inefficiencies in retrieval and knowledge graph construction, as part of a broader discussion on enhancing RAG systems through advanced chunking techniques and contextual retrieval methods.\n"
     ]
    }
   ],
   "source": [
    "for i, node in enumerate(nodes):\n",
    "    print(f\"\\n--- Chunk {i+1} ---\")\n",
    "    print(\"Text:\", node.text)\n",
    "    print(\"Local Context:\", node.metadata.get(\"local_context\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f92fda5",
   "metadata": {},
   "source": [
    "### Lets run the asynchronous version with parallel LLM calls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54265ea8",
   "metadata": {},
   "outputs": [],
   "source": [
    "parser.llm_workers = 4\n",
    "start_time = time.time()\n",
    "nodes = await parser.aget_nodes_from_documents([document], show_progress=True)\n",
    "end_time = time.time()\n",
    "print(f\"Time taken to parse: {end_time - start_time} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec34d716",
   "metadata": {},
   "source": [
    "## Lets inspect the chunks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bc38c96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- Chunk 1 ---\n",
      "Text: Constructing accurate knowledge graphs from long texts and low-resource languages is challenging, as large language models (LLMs) experience degraded performance with longer input chunks. This problem is amplified in low-resource settings where data scarcity hinders accurate entity and relationship extraction. Contextual retrieval methods, while improving retrieval accuracy, struggle with long documents. They truncate critical information in texts exceeding maximum context lengths of LLMs, significantly limiting knowledge graph construction. We introduce SLIDE (Sliding Localized Information for Document Extraction), a chunking method that processes long documents by generating local context through overlapping windows. SLIDE ensures that essential contextual information is retained, enhancing knowledge graph extraction from documents exceeding LLM context limits. It significantly improves GraphRAG performance, achieving a 24% increase in entity extraction and a 39% improvement in relationship extraction for English. For Afrikaans, a low-resource language, SLIDE achieves a 49% increase in entity extraction and an 82% improvement in relationship extraction.\n",
      "Local Context: assistant: The chunk provided introduces SLIDE (Sliding Localized Information for Document Extraction), a method that addresses the challenges of constructing accurate knowledge graphs from long texts and low-resource languages. It highlights how SLIDE improves knowledge graph extraction by processing long documents with overlapping windows, enhancing entity and relationship extraction performance significantly for both English and Afrikaans languages within the GraphRAG framework.\n",
      "\n",
      "--- Chunk 2 ---\n",
      "Text: Furthermore, it improves upon state-of-the-art in question-answering metrics such as comprehensiveness, diversity and empowerment, demonstrating its effectiveness in multilingual and resource-constrained settings.\n",
      "\n",
      " Since SLIDE enhances knowledge graph construction in GraphRAG systems through contextual chunking, we first discuss related work in GraphRAG and chunking, highlighting their strengths and limitations. This sets the stage for our approach, which builds on GraphRAG by using overlapping windows to improve entity and relationship extraction. 2.1 GraphRAG and Knowledge Graphs. GraphRAG (Edge et al., 2024) is an advanced RAG framework that integrates knowledge graphs with large language models (LLMs) (Trajanoska et al., 2023) to enhance reasoning and contextual understanding.\n",
      "Local Context: assistant: The chunk provided discusses how SLIDE enhances knowledge graph construction in GraphRAG systems through contextual chunking. It also introduces related work in GraphRAG and chunking, setting the stage for the approach that builds on GraphRAG by using overlapping windows to improve entity and relationship extraction.\n",
      "\n",
      "--- Chunk 3 ---\n",
      "Text: Unlike traditional RAG systems, GraphRAG builds a knowledge graph with entities as nodes and relationships as edges, enabling precise and context-rich responses by leveraging the graph’s structure (Edge et al., 2024; Wu et al., 2024).\n",
      " Large language models (LLMs), such as GPT-4, show reduced effectiveness in entity and relationship extraction as input chunk lengths increase, degrading accuracy for longer texts (Edge et al., 2024). They also struggle with relationship extraction in low-resource languages, limiting their applicability (Chen et al., 2024; Jinensibieke et al., 2024). Building upon this work, our approach further enhances knowledge graph extraction by incorporating localized context which improves entity and relationship extraction. 2.2 Contextual Chunking. Recent work in RAG systems has explored advanced chunking techniques to enhance retrieval and knowledge graph construction. Günther et al.\n",
      "Local Context: assistant: The chunk provided discusses how GraphRAG differs from traditional RAG systems by constructing knowledge graphs with entities as nodes and relationships as edges, leading to precise responses. It also highlights the challenges faced by large language models in entity and relationship extraction, especially in longer texts and low-resource languages. The approach presented in the chunk aims to enhance knowledge graph extraction by incorporating localized context to improve entity and relationship extraction, building upon existing research in contextual chunking techniques within RAG systems.\n",
      "\n",
      "--- Chunk 4 ---\n",
      "Text: (2024) implemented late chunking, where entire documents are embedded to capture global context before splitting into chunks, improving retrieval by emphasizing document-level coherence.\n",
      " However, this focus on global embeddings is less suited for knowledge graph construction. Our method instead uses localized context from raw text to retain meaningful relationships for improved entity and relationship extraction. Wu et al. (2024) introduced a hybrid chunking approach for Medical Graph RAG, combining structural markers like paragraphs with semantic coherence to produce self-contained chunks. While effective, this approach relies on predefined boundaries. Our method extends this by generating contextual information from neighboring chunks, enhancing the completeness of knowledge graph construction. Contextual retrieval (Anthropic, 2024) improves accuracy but struggles with longer documents, as embedding each chunk with full document context is computationally expensive and truncates critical information with documents exceeding maximum context length of the model (Jiang et al., 2024; Li et al., 2024).\n",
      "Local Context: assistant: This chunk discusses different approaches to chunking in the context of knowledge graph construction within RAG systems. It contrasts the use of global embeddings for document-level coherence with the utilization of localized context for improved entity and relationship extraction. Additionally, it mentions a hybrid chunking approach introduced by Wu et al. for Medical Graph RAG, highlighting the importance of generating contextual information from neighboring chunks to enhance knowledge graph completeness.\n",
      "\n",
      "--- Chunk 5 ---\n",
      "Text: Our overlapping window-based approach addresses these inefficiencies, improving performance in both retrieval and knowledge graph construction.\n",
      "\n",
      "Local Context: assistant: The chunk provided discusses an overlapping window-based approach that addresses inefficiencies in retrieval and knowledge graph construction, aiming to improve performance within the broader context of advanced chunking techniques and knowledge graph extraction strategies discussed in the document.\n"
     ]
    }
   ],
   "source": [
    "for i, node in enumerate(nodes):\n",
    "    print(f\"\\n--- Chunk {i+1} ---\")\n",
    "    print(\"Text:\", node.text)\n",
    "    print(\"Local Context:\", node.metadata.get(\"local_context\"))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama-index-HvjaGyNf-py3.10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
